// 仪表板功能
class Dashboard {
    constructor() {
        this.currentPage = 'overview';
        this.pages = new Map();
        this.init();
    }

    async init() {
        console.log('🚀 Dashboard 开始初始化...');
        
        // 检查认证状态
        console.log('🔐 检查认证状态...');
        const isAuth = await authService.checkAuthAndRedirect();
        if (!isAuth) {
            console.log('❌ 认证失败，停止初始化');
            return;
        }
        console.log('✅ 认证通过');

        // 初始化用户信息
        console.log('👤 初始化用户信息...');
        await this.initUserInfo();
        
        // 初始化导航
        console.log('🧭 初始化导航...');
        this.initNavigation();
        
        // 初始化退出登录
        console.log('🚪 初始化退出登录...');
        this.initLogout();
        
        // 加载概览数据
        console.log('📊 加载概览数据...');
        await this.loadOverviewData();
        
        // 注册页面
        console.log('📄 注册页面...');
        this.registerPages();
        
        console.log('🎉 Dashboard 初始化完成！');
    }

    async initUserInfo() {
        try {
            const user = await authService.getCurrentUser();
            if (user) {
                document.getElementById('userWelcome').textContent = `欢迎回来，${user.full_name || user.username}！`;
                document.getElementById('userInitial').textContent = (user.full_name || user.username).charAt(0).toUpperCase();
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    }

    initNavigation() {
        const navItems = document.querySelectorAll('.nav-item a');
        const actionBtns = document.querySelectorAll('.action-btn');

        // 导航栏点击事件
        navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const page = item.dataset.page;
                if (page) {
                    this.navigateToPage(page);
                }
            });
        });

        // 快速操作按钮点击事件
        actionBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const page = btn.dataset.page;
                if (page) {
                    this.navigateToPage(page);
                }
            });
        });
    }

    initLogout() {
        console.log('🔧 正在初始化退出登录功能...');
        
        const logoutBtn = document.getElementById('logoutBtn');
        
        if (!logoutBtn) {
            console.error('❌ 找不到退出登录按钮 (id=logoutBtn)');
            return;
        }
        
        console.log('✅ 找到退出登录按钮，正在绑定事件...');
        
        logoutBtn.addEventListener('click', async () => {
            console.log('🔔 退出登录按钮被点击');
            
            if (confirm('确定要退出登录吗？')) {
                console.log('👤 用户确认退出登录');
                
                // 显示加载状态
                const originalText = logoutBtn.textContent;
                logoutBtn.textContent = '退出中...';
                logoutBtn.disabled = true;
                
                try {
                    console.log('🔄 开始调用logout方法...');
                    // 调用logout方法
                    await authService.logout();
                    console.log('✅ logout方法调用完成');
                    
                    // 短暂延迟后跳转，让用户看到成功消息
                    setTimeout(() => {
                        console.log('🔄 跳转到登录页面...');
                        window.location.href = '/';
                    }, 1500);
                } catch (error) {
                    console.error('❌ 退出登录失败:', error);
                    // 即使失败也要跳转到登录页
                    window.location.href = '/';
                } finally {
                    // 恢复按钮状态（虽然通常会跳转，但以防万一）
                    logoutBtn.textContent = originalText;
                    logoutBtn.disabled = false;
                }
            } else {
                console.log('❌ 用户取消退出登录');
            }
        });
        
        console.log('✅ 退出登录功能初始化完成');
    }

    navigateToPage(pageName) {
        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        
        const navItem = document.querySelector(`[data-page="${pageName}"]`).closest('.nav-item');
        if (navItem) {
            navItem.classList.add('active');
        }

        // 加载页面内容
        this.loadPage(pageName);
        this.currentPage = pageName;
    }

    async loadPage(pageName) {
        const contentArea = document.getElementById('contentArea');
        
        try {
            // 显示加载状态
            contentArea.innerHTML = '<div class="loading">加载中...</div>';
            
            // 根据页面名称加载不同内容
            switch (pageName) {
                case 'overview':
                    await this.loadOverviewPage();
                    break;
                case 'chat':
                    await this.loadChatPage();
                    break;
                case 'knowledge':
                    await this.loadKnowledgePage();
                    break;
                case 'writing':
                    await this.loadWritingPage();
                    break;
                case 'profile':
                    await this.loadProfilePage();
                    break;
                default:
                    contentArea.innerHTML = '<div class="page-content"><h1>页面不存在</h1></div>';
            }
        } catch (error) {
            console.error('加载页面失败:', error);
            contentArea.innerHTML = '<div class="page-content"><h1>加载失败</h1><p>请刷新页面重试</p></div>';
        }
    }

    async loadOverviewPage() {
        try {
            // 重新创建概览页面的内容
            const contentArea = document.getElementById('contentArea');
            contentArea.innerHTML = `
                <div class="page-content" id="overviewContent">
                    <h1>平台概览</h1>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon">📚</div>
                            <div class="stat-info">
                                <h3>知识库数量</h3>
                                <p class="stat-number" id="kbCount">0</p>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">📄</div>
                            <div class="stat-info">
                                <h3>文档数量</h3>
                                <p class="stat-number" id="docCount">0</p>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">📝</div>
                            <div class="stat-info">
                                <h3>模板数量</h3>
                                <p class="stat-number" id="templateCount">0</p>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">💬</div>
                            <div class="stat-info">
                                <h3>对话次数</h3>
                                <p class="stat-number" id="chatCount">0</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="quick-actions">
                        <h2>快速操作</h2>
                        <div class="action-buttons">
                            <button class="action-btn" data-page="knowledge">
                                <i class="icon">➕</i>
                                创建知识库
                            </button>
                            <button class="action-btn" data-page="chat">
                                <i class="icon">💬</i>
                                开始对话
                            </button>
                            <button class="action-btn" data-page="writing">
                                <i class="icon">✍️</i>
                                智能写作
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // 重新绑定快速操作按钮
            this.initNavigation();
            
            // 加载统计数据
            await this.loadOverviewData();
            
            console.log('✅ 概览页面加载完成');
            
        } catch (error) {
            console.error('❌ 加载概览页面失败:', error);
            const contentArea = document.getElementById('contentArea');
            contentArea.innerHTML = `
                <div class="page-content">
                    <h1>概览</h1>
                    <div class="error-message">
                        <div class="error-icon">❌</div>
                        <h3>加载失败</h3>
                        <p>无法加载概览页面，请稍后重试。</p>
                        <button class="retry-btn" onclick="dashboard.loadOverviewPage()">重新加载</button>
                    </div>
                </div>
            `;
        }
    }

    async loadChatPage() {
        const contentArea = document.getElementById('contentArea');
        
        try {
            // 显示加载状态
            contentArea.innerHTML = '<div class="loading">正在加载智能问答...</div>';
            
            // 获取Dify配置
            const configResponse = await authService.authenticatedFetch('/api/auth/config');
            if (!configResponse || !configResponse.ok) {
                throw new Error('获取配置失败');
            }
            
            const config = await configResponse.json();
            const difyIframeUrl = config.dify_iframe_url;
            
            if (!difyIframeUrl) {
                // 如果没有配置Dify URL，显示提示信息
                contentArea.innerHTML = `
                    <div class="page-content">
                        <h1>智能问答</h1>
                        <div class="config-notice">
                            <div class="notice-icon">⚙️</div>
                            <h3>需要配置Dify服务</h3>
                            <p>请在后端配置文件中设置 <code>DIFY_IFRAME_URL</code> 来启用智能问答功能。</p>
                            <div class="config-example">
                                <strong>配置示例：</strong><br>
                                <code>DIFY_IFRAME_URL = "https://your-dify-domain.com/chatbot/your-app-id"</code>
                            </div>
                        </div>
                    </div>
                `;
                return;
            }
            
            // 渲染Dify iframe
            contentArea.innerHTML = `
                <div class="page-content">
                    <h1>智能问答</h1>
                    <div class="dify-chat-container">
                        <iframe
                            src="${difyIframeUrl}"
                            style="width: 100%; height: 100%; min-height: 700px; border: none; border-radius: 8px;"
                            frameborder="0"
                            allow="microphone">
                        </iframe>
                    </div>
                </div>
            `;
            
            console.log('✅ Dify智能问答界面加载完成');
            
        } catch (error) {
            console.error('❌ 加载智能问答页面失败:', error);
            contentArea.innerHTML = `
                <div class="page-content">
                    <h1>智能问答</h1>
                    <div class="error-message">
                        <div class="error-icon">❌</div>
                        <h3>加载失败</h3>
                        <p>无法加载智能问答界面，请稍后重试。</p>
                        <button class="retry-btn" onclick="dashboard.loadChatPage()">重新加载</button>
                    </div>
                </div>
            `;
        }
    }

    async loadKnowledgePage() {
        const contentArea = document.getElementById('contentArea');
        contentArea.innerHTML = `
            <div class="page-content">
                <div class="page-header">
                    <h1>知识库管理</h1>
                    <button class="btn-primary" id="createKbBtn">创建知识库</button>
                </div>
                <div class="knowledge-bases" id="knowledgeBases">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        `;
        
        // 加载知识库列表
        await this.loadKnowledgeBases();
        
        // 绑定创建按钮
        document.getElementById('createKbBtn').addEventListener('click', () => {
            this.showCreateKbModal();
        });
    }

    async loadWritingPage() {
        const contentArea = document.getElementById('contentArea');
        contentArea.innerHTML = `
            <div class="page-content">
                <div class="page-header">
                    <h1>智能写作</h1>
                    <button class="btn-primary" id="createTemplateBtn">创建模板</button>
                </div>
                <div class="writing-section">
                    <div class="templates-section">
                        <h2>我的模板</h2>
                        <div class="templates-list" id="templatesList">
                            <div class="loading">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 加载模板列表
        await this.loadTemplates();
    }

    async loadProfilePage() {
        const contentArea = document.getElementById('contentArea');
        const user = await authService.getCurrentUser();
        
        contentArea.innerHTML = `
            <div class="page-content">
                <h1>个人信息</h1>
                <div class="profile-section">
                    <div class="profile-info">
                        <div class="info-item">
                            <label>用户名：</label>
                            <span>${user.username}</span>
                        </div>
                        <div class="info-item">
                            <label>邮箱：</label>
                            <span>${user.email || '未设置'}</span>
                        </div>
                        <div class="info-item">
                            <label>姓名：</label>
                            <span>${user.full_name || '未设置'}</span>
                        </div>
                        <div class="info-item">
                            <label>注册时间：</label>
                            <span>${new Date(user.created_at).toLocaleString()}</span>
                        </div>
                        <div class="info-item">
                            <label>用户状态：</label>
                            <span class="status ${user.is_active ? 'active' : 'inactive'}">
                                ${user.is_active ? '正常' : '已禁用'}
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    async loadOverviewData() {
        try {
            console.log('📊 开始加载概览数据...');
            
            // 设置默认值
            const defaultCounts = {
                kbCount: 0,
                docCount: 0,
                templateCount: 0,
                chatCount: 0
            };
            
            // 安全地更新元素内容
            const updateCount = (elementId, count) => {
                const element = document.getElementById(elementId);
                if (element) {
                    element.textContent = count;
                } else {
                    console.warn(`⚠️ 元素 ${elementId} 不存在`);
                }
            };
            
            // 尝试加载知识库数据
            try {
                const kbResponse = await authService.authenticatedFetch('/api/knowledge-bases/');
                if (kbResponse && kbResponse.ok) {
                    const kbs = await kbResponse.json();
                    updateCount('kbCount', kbs.length);
                    
                    // 计算总文档数
                    let totalDocs = 0;
                    for (const kb of kbs) {
                        try {
                            const docsResponse = await authService.authenticatedFetch(`/api/documents/${kb.id}/documents`);
                            if (docsResponse && docsResponse.ok) {
                                const docs = await docsResponse.json();
                                totalDocs += docs.length;
                            }
                        } catch (docError) {
                            console.warn(`⚠️ 获取知识库 ${kb.id} 的文档数失败:`, docError);
                        }
                    }
                    updateCount('docCount', totalDocs);
                } else {
                    console.warn('⚠️ 获取知识库数据失败');
                    updateCount('kbCount', defaultCounts.kbCount);
                    updateCount('docCount', defaultCounts.docCount);
                }
            } catch (error) {
                console.warn('⚠️ 知识库API调用失败:', error);
                updateCount('kbCount', defaultCounts.kbCount);
                updateCount('docCount', defaultCounts.docCount);
            }

            // 尝试加载模板数据
            try {
                const templatesResponse = await authService.authenticatedFetch('/api/templates/');
                if (templatesResponse && templatesResponse.ok) {
                    const templates = await templatesResponse.json();
                    updateCount('templateCount', templates.length);
                } else {
                    console.warn('⚠️ 获取模板数据失败');
                    updateCount('templateCount', defaultCounts.templateCount);
                }
            } catch (error) {
                console.warn('⚠️ 模板API调用失败:', error);
                updateCount('templateCount', defaultCounts.templateCount);
            }

            // 尝试加载聊天数据
            try {
                const chatResponse = await authService.authenticatedFetch('/api/chat/sessions');
                if (chatResponse && chatResponse.ok) {
                    const sessions = await chatResponse.json();
                    updateCount('chatCount', sessions.length);
                } else {
                    console.warn('⚠️ 获取聊天数据失败');
                    updateCount('chatCount', defaultCounts.chatCount);
                }
            } catch (error) {
                console.warn('⚠️ 聊天API调用失败:', error);
                updateCount('chatCount', defaultCounts.chatCount);
            }
            
            console.log('✅ 概览数据加载完成');
            
        } catch (error) {
            console.error('❌ 加载概览数据失败:', error);
            // 即使出错也要设置默认值，避免显示错误的数据
            ['kbCount', 'docCount', 'templateCount', 'chatCount'].forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.textContent = '0';
                }
            });
        }
    }

    async loadKnowledgeBases() {
        try {
            const response = await authService.authenticatedFetch('/api/knowledge-bases/');
            if (response && response.ok) {
                const kbs = await response.json();
                this.renderKnowledgeBases(kbs);
            }
        } catch (error) {
            console.error('加载知识库失败:', error);
        }
    }

    renderKnowledgeBases(kbs) {
        const container = document.getElementById('knowledgeBases');
        
        if (kbs.length === 0) {
            container.innerHTML = '<p class="empty-state">还没有知识库，点击"创建知识库"开始吧！</p>';
            return;
        }

        const kbCards = kbs.map(kb => `
            <div class="kb-card" data-kb-id="${kb.id}">
                <h3>${kb.name}</h3>
                <p>${kb.description || '暂无描述'}</p>
                <div class="kb-meta">
                    <span>向量库: ${kb.vector_db_type}</span>
                    <span>模型: ${kb.embedding_model}</span>
                </div>
                <div class="kb-actions">
                    <button class="btn-secondary" onclick="dashboard.viewKnowledgeBase(${kb.id})">查看</button>
                    <button class="btn-secondary" onclick="dashboard.editKnowledgeBase(${kb.id})">编辑</button>
                    <button class="btn-danger" onclick="dashboard.deleteKnowledgeBase(${kb.id})">删除</button>
                </div>
            </div>
        `).join('');

        container.innerHTML = kbCards;
    }

    async loadTemplates() {
        try {
            const response = await authService.authenticatedFetch('/api/templates/');
            if (response && response.ok) {
                const templates = await response.json();
                this.renderTemplates(templates);
            }
        } catch (error) {
            console.error('加载模板失败:', error);
        }
    }

    renderTemplates(templates) {
        const container = document.getElementById('templatesList');
        
        if (templates.length === 0) {
            container.innerHTML = '<p class="empty-state">还没有模板，点击"创建模板"开始吧！</p>';
            return;
        }

        const templateCards = templates.map(template => `
            <div class="template-card">
                <h3>${template.name}</h3>
                <p>${template.description || '暂无描述'}</p>
                <div class="template-meta">
                    <span>类型: ${template.template_type}</span>
                    <span>格式: ${template.format_type}</span>
                </div>
                <div class="template-actions">
                    <button class="btn-primary" onclick="dashboard.useTemplate(${template.id})">使用</button>
                    <button class="btn-secondary" onclick="dashboard.editTemplate(${template.id})">编辑</button>
                </div>
            </div>
        `).join('');

        container.innerHTML = templateCards;
    }

    showCreateKbModal() {
        // TODO: 实现创建知识库模态框
        const name = prompt('请输入知识库名称:');
        if (name) {
            this.createKnowledgeBase(name);
        }
    }

    async createKnowledgeBase(name, description = '') {
        try {
            const response = await authService.authenticatedFetch('/api/knowledge-bases/', {
                method: 'POST',
                body: JSON.stringify({
                    name: name,
                    description: description
                })
            });

            if (response && response.ok) {
                alert('知识库创建成功！');
                await this.loadKnowledgeBases();
            }
        } catch (error) {
            console.error('创建知识库失败:', error);
            alert('创建知识库失败，请稍后重试。');
        }
    }

    registerPages() {
        // 注册页面内容，用于路由
        this.pages.set('overview', () => this.loadOverviewPage());
        this.pages.set('chat', () => this.loadChatPage());
        this.pages.set('knowledge', () => this.loadKnowledgePage());
        this.pages.set('writing', () => this.loadWritingPage());
        this.pages.set('profile', () => this.loadProfilePage());
    }
}

// 创建全局仪表板实例
const dashboard = new Dashboard(); 